package com.jiutong.meipengdai.ui.fragments;

import android.Manifest;
import android.content.ContentValues;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.jiutong.meipengdai.R;
import com.jiutong.meipengdai.base.BaseFragment;
import com.jiutong.meipengdai.common.Constants;
import com.jiutong.meipengdai.entity.AccountInfoRespond;
import com.jiutong.meipengdai.http.model.interfaces.MyAccountBiz;
import com.jiutong.meipengdai.http.present.MyAccountPresent;
import com.jiutong.meipengdai.ui.activitys.EvaluateActivity;
import com.jiutong.meipengdai.ui.activitys.GaodeMapActivity;
import com.jiutong.meipengdai.ui.activitys.HouseListActivity;
import com.jiutong.meipengdai.ui.activitys.LoanApplyActivity;
import com.jiutong.meipengdai.ui.activitys.MsgCenterActivity;
import com.jiutong.meipengdai.utils.NumUilt;
import com.jiutong.meipengdai.utils.PermissionUtil;
import com.jiutong.meipengdai.utils.SpConfig;
import com.jiutong.meipengdai.views.CircleView;
import com.jiutong.meipengdai.views.rollviewpager.AdvsPagerAdapter;
import com.jiutong.meipengdai.views.rollviewpager.ColorPointHintView;
import com.jiutong.meipengdai.views.rollviewpager.OnItemClickListener;
import com.jiutong.meipengdai.views.rollviewpager.RollPagerView;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

import static android.app.Activity.RESULT_OK;

/**
 * Created by suxi on 2017/5/24.
 */

public class HomeFragment extends BaseFragment implements View.OnClickListener, MyAccountBiz {

    private Button btn_apply;
    private View tv_dingwei;
    private View tv_takephoto;
    private RelativeLayout rl_centerbg;
    private RelativeLayout rlCustomView;
    private TextView tvLoanDesc;
    private LinearLayout ll_money_desc;
    private float totalAmount = 0;
    private TextView tvLimit;
    private MyAccountPresent present;
    private CircleView circleview;
    private RollPagerView mRollViewPager; //轮播图
    private boolean mHidden;
    private String imgPath; //相片存储路径
    private int REQUEST_CAMERA = 1 << 2;
    private AccountInfoRespond.DataBean respond;
    private TextView tvUseableMoney; //可用额度
    private TextView tvUsedMoney; //已用额度
    private TextView tvEvaluate; //房产评估
    private RelativeLayout rl_msg_icon;

    @Override
    protected int getLayoutResouceId() {
        return R.layout.fragment_home;
    }

    @Override
    protected void initView() {
        super.initView();
        btn_apply = findViewById(R.id.btn_apply_loan);
        tv_dingwei = findViewById(R.id.tv_dingwei);
        tv_takephoto = findViewById(R.id.tv_take_photo);
        rl_centerbg = findViewById(R.id.rl_centerbg);
        rlCustomView = findViewById(R.id.rl_custom_view);
        tvLoanDesc = findViewById(R.id.tv_loan_desc);
        ll_money_desc = findViewById(R.id.ll_money_desc);
        tvLimit = findViewById(R.id.tv_limit);
        circleview = findViewById(R.id.circleview);
        mRollViewPager = findViewById(R.id.iv_ads);
        tvUseableMoney = findViewById(R.id.tv_usable_money);
        tvUsedMoney = findViewById(R.id.tv_used_money);
        tvEvaluate = findViewById(R.id.tv_evaluate);
        mRollViewPager = findViewById(R.id.iv_ads);
        rl_msg_icon = findViewById(R.id.rl_msg_icon);
        present = new MyAccountPresent(mActivity, this);

        //设置透明度
        mRollViewPager.setAnimationDurtion(500);
        //设置适配器
        mRollViewPager.setAdapter(new AdvsPagerAdapter(mRollViewPager));

        //隐藏指示器
        mRollViewPager.setHintView(new ColorPointHintView(mActivity, 0xfff09738, 0xff999999));

        mRollViewPager.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(int position) {

            }
        });
    }

    @Override
    protected void initEvent() {
        super.initEvent();
        btn_apply.setOnClickListener(this);
        tv_dingwei.setOnClickListener(this);
        tv_takephoto.setOnClickListener(this);
        tvEvaluate.setOnClickListener(this);
        circleview.setOnClickListener(this);
        rl_msg_icon.setOnClickListener(this);
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if(savedInstanceState != null)
            imgPath = savedInstanceState.getString("picpath");
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_apply_loan:
                //额度不为零，跳转到申请贷款，否则进入额度评估
                if ("申请贷款".equals(btn_apply.getText().toString())) {
                    openActivity(LoanApplyActivity.class);
                } else {
                    openActivity(EvaluateActivity.class);
                }
                break;
            case R.id.tv_dingwei:
                openActivity(GaodeMapActivity.class);
                break;
            case R.id.tv_evaluate:
                openActivity(EvaluateActivity.class);
                break;
            case R.id.circleview:
                openActivity(HouseListActivity.class);
                break;
            case R.id.tv_take_photo:
                openCamera();
                break;
            case R.id.rl_msg_icon:
                openActivity(MsgCenterActivity.class);
                break;
        }
    }

    private void openCamera() {

        //检查系统是否开启了拍照位置权限;
        if (!PermissionUtil.checkSelfPermission(getActivity(), Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            return;
        }

        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss"); // 格式化时间
        String filename = format.format(date) + ".jpg";

        File fileFolder = new File(Environment.getExternalStorageDirectory()
                + "/jiutong/");
        if (!fileFolder.exists()) { // 如果目录不存在，则创建一个名为"finger"的目录
            fileFolder.mkdir();
        }

        File jpgFile = new File(fileFolder, filename);
        imgPath = jpgFile.getPath();

        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);// 启动系统相机

        int currentapiVersion = android.os.Build.VERSION.SDK_INT;
        if (currentapiVersion < 24) {
            // 从文件中创建uri
            Uri uri = Uri.fromFile(jpgFile);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        } else {
            //兼容android7.0 使用共享文件的形式
            ContentValues contentValues = new ContentValues(1);
            contentValues.put(MediaStore.Images.Media.DATA, jpgFile.getAbsolutePath());
            Uri uri = getActivity().getApplication().getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        }

        startActivityForResult(intent, REQUEST_CAMERA);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode != RESULT_OK)
            return;

        // 如果返回数据
        if (requestCode == REQUEST_CAMERA) { // 拍照数据
            Bundle bundle = new Bundle();
            bundle.putString("picpath", imgPath);
            openActivity(EvaluateActivity.class, bundle);
        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        outState.putString("picpath", imgPath);
        super.onSaveInstanceState(outState);
    }

    @Override
    public void onViewStateRestored(@Nullable Bundle savedInstanceState) {
        if (savedInstanceState != null) {
            imgPath = savedInstanceState.getString("picpath");
        }
        super.onViewStateRestored(savedInstanceState);
    }

    @Override
    public String getBankNum() {
        return null;
    }

    @Override
    public String getBankName() {
        return null;
    }

    @Override
    public String getCartStatus() {
        return null;
    }

    @Override
    public String getBankId() {
        return null;
    }

    @Override
    public String getMsgId() {
        return null;
    }

    @Override
    public String getLoanId() {
        return null;
    }

    @Override
    public String Consignee() {
        return null;
    }

    @Override
    public String getTelephone() {
        return null;
    }

    @Override
    public String getBigLocation() {
        return null;
    }

    @Override
    public String getDetail() {
        return null;
    }

    @Override
    public String getIsDefault() {
        return null;
    }

    @Override
    public String getOprType() {
        return null;
    }

    @Override
    public String getMainId() {
        return null;
    }


    @Override
    public void onSuccess(Object object) {
        AccountInfoRespond result = (AccountInfoRespond) object;
        respond = result.getData();
        //可贷额度
        float amountSum = Float.parseFloat(respond.getAmountSum()+"");
        //已贷额度
        float loanAmount = Float.parseFloat(respond.getLoanAmount()+"");

        //账户总额
        totalAmount = amountSum + loanAmount;

        if (totalAmount > 0) {
            rl_centerbg.setVisibility(View.GONE);
            tvLoanDesc.setVisibility(View.GONE);
            rlCustomView.setVisibility(View.VISIBLE);
            circleview.setCurrentDegree(loanAmount / totalAmount);
            circleview.invalidate();
            ll_money_desc.setVisibility(View.VISIBLE);
            tvEvaluate.setVisibility(View.VISIBLE);

            if (totalAmount >= 10000) {
                tvLimit.setText(NumUilt.formatFloat(totalAmount / 10000) + "");
            } else {
                tvLimit.setText(NumUilt.formatFloat(totalAmount) + "");
            }

            if (amountSum >= 10000) {
                tvUseableMoney.setText("可贷总额度(元) " + NumUilt.formatFloat(amountSum / 10000) + "万");
            } else {
                tvUseableMoney.setText("可贷总额度(元) " + NumUilt.formatFloat(amountSum));
            }

            if (loanAmount >= 10000) {
                tvUsedMoney.setText("已贷总额度(元) " + NumUilt.formatFloat(loanAmount / 10000) + "万");
            } else {
                tvUsedMoney.setText("已贷总额度(元) " + NumUilt.formatFloat(loanAmount));
            }

            btn_apply.setText("申请贷款");
        } else {
            rl_centerbg.setVisibility(View.VISIBLE);
            tvLoanDesc.setVisibility(View.VISIBLE);
            rlCustomView.setVisibility(View.GONE);
            ll_money_desc.setVisibility(View.GONE);
            tvEvaluate.setVisibility(View.GONE);
            btn_apply.setText("额度评估");
        }
    }

    @Override
    public void onError(Throwable e) {

        rl_centerbg.setVisibility(View.VISIBLE);
        tvLoanDesc.setVisibility(View.VISIBLE);
        rlCustomView.setVisibility(View.GONE);
        ll_money_desc.setVisibility(View.GONE);
        tvEvaluate.setVisibility(View.GONE);
        btn_apply.setText("额度评估");

    }

    @Override
    public void onResume() {
        super.onResume();
        if (mHidden)
            return;
        doNetWork();
    }

    public void doNetWork() {
        //登录之后才能请求网络
        if (!TextUtils.isEmpty(SpConfig.getInstance().getString(Constants.SESSIONID_STRING))) {
            present.getAccountInfo();
        } else {
            rl_centerbg.setVisibility(View.VISIBLE);
            tvLoanDesc.setVisibility(View.VISIBLE);
            rlCustomView.setVisibility(View.GONE);
            ll_money_desc.setVisibility(View.GONE);
            tvEvaluate.setVisibility(View.GONE);
            btn_apply.setText("额度评估");
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        mHidden = hidden;
        if (!hidden) {
            doNetWork();
        }
    }
}
